package com.lanou3g.demo.utils;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ValidationUtils {

    /*
    {
        "username": [
            "用户名不能为空",
            "用户名长度"
        ],
        "password": [

        ]
    }
     */
    public static Map<String, List<String>> handle(BindingResult result) {

        List<FieldError> errors = result.getFieldErrors();

        Map<String, List<String>> errorMap = new HashMap<>();

        for (FieldError error : errors) {

            String field = error.getField();
            String message = error.getDefaultMessage();

            List<String> messageList = errorMap.get(field);
            if (messageList != null) {
                messageList.add(message);
            } else {
                List<String> list = new ArrayList<>();
                list.add(message);
                errorMap.put(field, list);
            }
        }

        return errorMap;
    }

}
